/**
 * Created by rubin on 2019/1/21.
 */

'use strict';

var page

layui.use(['form', 'element', 'table', 'laydate'], function () {
    var form = layui.form,
        element = layui.element,
        table = layui.table,
        laydate = layui.laydate
    page = {
        data: {},
        start: function () {
            this.onLoad()
            this.bindEvent()
        },
        onLoad: function () {
            this.loadMonthResultsData()
            this.loadCustomerData()
            this.loadCustomerTransferData()
            this.loadExchangeData()
            this.initDateComponent()
            this.loadScheduleTableData()
            this.loadWorkBriefingDataByType()
        },
        bindEvent: function () {
            var _this = this
            $('#schedule_add_btn').click(function () {
                _this.openForm(true)
            })
        },
        loadMonthResultsData: function () {
            sinoUtil.sendHttp(sinoUtil.httpPrefix + '/api-business/getMonthPerformanceData', 'get', {}, function (res) {
                if (res.status == 0) {
                    var data = new Array()
                    data.push(res.data.monthDone)
                    data.push(res.data.monthTarget)
                    var option = {
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'shadow'
                            },
                            formatter: function (params) {
                                var result = ''
                                result = result + params[0].name + ' : ' + params[0].value + '元'
                                return result
                            }
                        },
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '3%',
                            containLabel: true
                        },
                        xAxis: {
                            type: 'value',
                            boundaryGap: [0, 0.01]
                        },
                        yAxis: {
                            type: 'category',
                            data: ['订单金额', '目标金额']
                        },
                        series: [
                            {
                                type: 'bar',
                                data: data,
                                barWidth: 30,
                                itemStyle: {
                                    normal: {
                                        color: function (params) {
                                            var colorList = ['#5FB878', '#4ad2ff']
                                            return colorList[params.dataIndex]
                                        }
                                    }
                                }

                            }
                        ]
                    }
                    echarts.init(document.getElementById('month_results_content')).setOption(option)
                } else if (res.status == 10 || res.status == 11) {
                    window.parent.location.href = '/system/login'
                } else {
                    layer.msg('获取本月业绩数据失败', {
                        icon: 2,
                        time: 2000 //2秒关闭（如果不配置，默认是3秒）
                    })
                }
            }, function (error) {
                layer.msg('获取本月业绩数据失败', {
                    icon: 2,
                    time: 2000 //2秒关闭（如果不配置，默认是3秒）
                })
            }, true)
        },
        loadCustomerData: function () {
            sinoUtil.sendHttp(sinoUtil.httpPrefix + '/api-business/getMyCustomersData', 'get', {}, function (res) {
                if (res.status == 0) {
                    var data = new Array()
                    data.push({
                        value: res.data.oneLevel,
                        name: '一星'
                    })
                    data.push({
                        value: res.data.twoLevel,
                        name: '二星'
                    })
                    data.push({
                        value: res.data.threeLevel,
                        name: '三星'
                    })
                    data.push({
                        value: res.data.fourLevel,
                        name: '四星'
                    })
                    data.push({
                        value: res.data.fiveLevel,
                        name: '五星'
                    })
                    var option = {
						 color:['#d83104','#2d66cd','#05901b','#ec3973','#fcb700'],
                        tooltip: {
                            trigger: 'item',
                            formatter: "{a} <br/>{b} : {c} ({d}%)"
                        },
                        legend: {
                        	top:'center',
							itemGap:30,
                            orient: 'vertical',
                            left: '3.8%',
                            textStyle: {
                            	 fontSize:14,
            		        },
                            data: ['一星', '二星', '三星', '四星', '五星']
                        },
                        series: [
                            {
                                name: '客户资源',
                                type: 'pie',
                                radius: '55%',
                                center: ['50%', '60%'],
                                data: data,
                                itemStyle: {
                                    emphasis: {
                                        shadowBlur: 10,
                                        shadowOffsetX: 0,
                                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                }
                            }
                        ]
                    }
                    echarts.init(document.getElementById('customer_content')).setOption(option)
                } else if (res.status == 10 || res.status == 11) {
                    window.parent.location.href = '/system/login'
                } else {
                    layer.msg('获取客户资源数据失败', {
                        icon: 2,
                        time: 2000 //2秒关闭（如果不配置，默认是3秒）
                    })
                }
            }, function (error) {
                layer.msg('获取客户资源数据失败', {
                    icon: 2,
                    time: 2000 //2秒关闭（如果不配置，默认是3秒）
                })
            }, true)
        },
        loadCustomerTransferData: function () {
            sinoUtil.sendHttp(sinoUtil.httpPrefix + '/api-business/getCustomerTransferData', 'get', {}, function (res) {
                if (res.status == 0) {
                    $('#transfer_in_count').text('').text(res.data.customerInCount)
                    $('#transfer_out_count').text('').text(res.data.customerOutCount)
                    $('#fifteenDayNoContactCustomer').text('').text(res.data.fifteenDayNoContactCustomerCount)
                    $('#sixtyDayNoCreateOrderCustomer').text('').text(res.data.sixtyDayNoCreateOrderCustomerCount)
                    $('#mail_unread_count').text('').text(res.data.unReadEmailCount)
                } else if (res.status == 10 || res.status == 11) {
                    window.parent.location.href = '/system/login'
                } else {
                    layer.msg('获取客户流转数据失败', {
                        icon: 2,
                        time: 2000 //2秒关闭（如果不配置，默认是3秒）
                    })
                }
            }, function (error) {
                layer.msg('获取客户流转数据失败', {
                    icon: 2,
                    time: 2000 //2秒关闭（如果不配置，默认是3秒）
                })
            }, true)
        },
        loadExchangeData: function () {
            sinoUtil.sendHttp(sinoUtil.httpPrefix + '/api-business/getAllExchangeRate', 'get', {}, function (res) {
                if (res.status == 0) {
                    var options = ''
                    layui.each(res.data, function (index, item) {
                        options = options
                            + '<option value="'
                            + item.exchangeRate
                            + '">'
                            + item.currency
                            + '</option>'
                    })
                    $('#currencySelect').empty().append(options)
                    $('#exchange_money').text('').text(res.data[0].exchangeRate)
                    form.on('select(currency)', function (data) {
                        // console.log(data.elem); //得到checkbox原始DOM对象
                        // console.log(data.elem.checked); //是否被选中，true或者false
                        // console.log(data.value); //复选框value值，也可以通过data.elem.value得到
                        // console.log(data.othis); //得到美化后的DOM对象
                        $('#exchange_money').text('').text(data.value)
                    })
                    form.render()
                } else if (res.status == 10 || res.status == 11) {
                    window.parent.location.href = '/system/login'
                } else {
                    layer.msg('获取汇率信息失败', {
                        icon: 2,
                        time: 2000 //2秒关闭（如果不配置，默认是3秒）
                    })
                }
            })
        },
        loadScheduleTableData: function () {
            var _this = this
            sinoUtil.sendHttp(sinoUtil.httpPrefix + '/api-business/getScheduleData', 'get', {}, function (res) {
                if (res.status == 0) {
                    table.render({
                        elem: '#schedule_table'
                        , height: 254
                        , url: ''
                        , data: res.data
                        , page: false
                        , cols: [[
                            {
                                field: 'scheduleContent',
                                title: '日程内容',
                                width: '20%',
                                align: 'center'
                            },
                            {
                                field: 'startDate',
                                title: '开始时间',
                                width: '28%',
                                align: 'center',
                                templet  : function (d) {
                                    var date = new Date(d.startDate),
                                        Y = date.getFullYear() + '-',
                                        M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-',
                                        D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ',
                                        h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':',
                                        m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':',
                                        s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
                                    return Y + M + D + h + m + s
                                }
                            },
                            {
                                field: 'endDate',
                                title: '结束时间',
                                width: '28%',
                                align: 'center',
                                templet  : function (d) {
                                    var date = new Date(d.endDate),
                                        Y = date.getFullYear() + '-',
                                        M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-',
                                        D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ',
                                        h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':',
                                        m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':',
                                        s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
                                    return Y + M + D + h + m + s
                                }
                            },
                            {
                                title: '操作',
                                align: 'center',
                                width: '24%',
                                toolbar: '#schdule_table_tool_bar'
                            }
                        ]],
                        text: {
                            none: '暂无相关数据'
                        }
                    })
                    table.on('tool(schedule)', function (obj) {
                        var layEvent = obj.event,
                            data = obj.data
                        if (layEvent === 'detail') {
                            layer.open({
                                title: '日程详情',
                                type: 1,
                                content: $('#detail_schedule_form_content'),
                                area: ['600px', '300px'],
                                btn: ['已完成'],
                                btnAlign: 'c',
                                shadeClose: true,
                                success: function (layero, index) {
                                    $('#detail_schedule_content').text('').text(data.scheduleContent)
                                    $('#detail_schedule_date').text('').text(_this.getDateStr(data.startDate) + ' 至 ' + _this.getDateStr(data.endDate))
                                },
                                yes: function (index, layero) {
                                    sinoUtil.sendHttp(sinoUtil.httpPrefix + '/api-business/saveScheduleData', 'post', {
                                        scheduleId: data.scheduleId,
                                        activeFlag: 2
                                    }, function (res) {
                                        if (res.status == 0) {
                                            layer.close(index)
                                            _this.loadScheduleTableData()
                                        } else if (res.status == 10 || res.status == 11) {
                                            window.parent.location.href = '/system/login'
                                        } else {
                                            layer.close(index)
                                            layer.msg('操作失败', {
                                                icon: 2,
                                                time: 2000 //2秒关闭（如果不配置，默认是3秒）
                                            })
                                        }
                                    }, function (error) {
                                        layer.close(index)
                                        layer.msg('操作失败', {
                                            icon: 2,
                                            time: 2000 //2秒关闭（如果不配置，默认是3秒）
                                        })
                                    }, false)
                                },
                                end: function () {

                                }
                            })
                        } else if (layEvent == 'edit') {
                            _this.data.editData = data
                            _this.openForm(false)
                        } else if (layEvent == 'delete') {
                            sinoUtil.sendHttp(sinoUtil.httpPrefix + '/api-business/deleteScheduleData', 'post', {
                                ids: data.scheduleId
                            }, function (res) {
                                if (res.status == 0) {
                                    _this.loadScheduleTableData()
                                } else if (res.status == 10 || res.status == 11) {
                                    window.parent.location.href = '/system/login'
                                } else {
                                    layer.msg('删除失败', {
                                        icon: 2,
                                        time: 2000 //2秒关闭（如果不配置，默认是3秒）
                                    })
                                }
                            }, function (error) {
                                layer.msg('删除失败', {
                                    icon: 2,
                                    time: 2000 //2秒关闭（如果不配置，默认是3秒）
                                })
                            }, true)
                        }
                    })
                } else if (res.status == 10 || res.status == 11) {
                    window.parent.location.href = '/system/login'
                } else {
                    layer.msg('获取日程信息失败', {
                        icon: 2,
                        time: 2000 //2秒关闭（如果不配置，默认是3秒）
                    })
                }
            }, function (error) {
                layer.msg('获取日程信息失败', {
                    icon: 2,
                    time: 2000 //2秒关闭（如果不配置，默认是3秒）
                })
            }, true)
        },
        getDateStr: function (date) {
            var date = new Date(date),
                Y = date.getFullYear() + '/',
                M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '/',
                D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ',
                h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':',
                m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':',
                s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
            return Y + M + D + h + m + s
        },
        validateForm: function () {
            if (!sinoUtil.validate($('#schedule_content').val(), 'require')) {
                $('#schedule_content').addClass("error")
                layer.msg('请填写日程内容', {icon: 2, anim: 6})
                return false
            } else {
                $('#schedule_content').removeClass("error")
            }
            return true
        },
        openForm: function (isAdd) {
            var _this = this,
                title = '新建日程',
                successTip = '新建成功',
                errorTip = '新建失败'
            if (!isAdd) {
                title = '编辑日程'
                successTip = '编辑成功'
                errorTip = '编辑失败'
            }
            layer.open({
                title: title,
                type: 1,
                content: $('#add_schedule_form_content'),
                area: ['600px', '300px'],
                btn: ['提交', '取消'],
                btnAlign: 'c',
                shadeClose: true,
                success: function (layero, index) {
                    if (isAdd) {
                        var date = new Date(),
                            Y = date.getFullYear() + '/',
                            M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '/',
                            D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ',
                            start = Y + M + D + '00:00:00',
                            end = Y + M + D + '23:59:59'
                        $('#schedule_date').val(start + ' 至 ' + end)
                    } else {
                        $('#schedule_date').val(_this.getDateStr(_this.data.editData.startDate) + ' 至 ' + _this.getDateStr(_this.data.editData.endDate))
                        $('#schedule_content').val(_this.data.editData.scheduleContent)
                    }
                },
                yes: function (index, layero) {
                    if (_this.validateForm()) {
                        var param = {
                            startDate: $('#schedule_date').val().split(' 至 ')[0],
                            endDate: $('#schedule_date').val().split(' 至 ')[1]
                        }
                        if (!isAdd) {
                            param.scheduleId = _this.data.editData.scheduleId
                        }
                        _this.data.index = sinoUtil.loading()
                        param.scheduleContent = $('#schedule_content').val()
                        sinoUtil.sendHttp(sinoUtil.httpPrefix + '/api-business/saveScheduleData', 'post', param, function (res) {
                            if (res.status == 0) {
                                layer.close(index)
                                sinoUtil.stopLoadingAndShowResult(_this.data.index, 1, successTip)
                                _this.loadScheduleTableData()
                            } else if (res.status == 10 || res.status == 11) {
                                layer.close(index)
                                window.parent.location.href = '/system/login'
                            } else {
                                sinoUtil.stopLoadingAndShowResult(_this.data.index, 2, res.msg)
                            }
                        }, function (error) {
                            sinoUtil.stopLoadingAndShowResult(_this.data.index, 2, errorTip)
                        }, false)
                    }
                },
                end: function () {
                    $('#schedule_content').val('').removeClass("error")
                    $('#schedule_date').val('')
                }
            })
        },
        initDateComponent: function () {
            laydate.render({
                elem: '#schedule_date'
                ,
                type: 'datetime'
                ,
                format: 'yyyy/MM/dd HH:mm:ss' //可任意组合
                ,
                range: '至' //或 range: '~' 来自定义分割字符
                ,
                calendar: true
                ,
                btns: ['confirm']
            })
        },
        loadWorkBriefingData: function (obj) {
            this.data.index = sinoUtil.loading()
            $(obj).addClass('active').siblings().removeClass('active')
            this.loadWorkBriefingDataByType($(obj).data('type'))
        },
        loadWorkBriefingDataByType: function (type) {
            var _this = this
            sinoUtil.sendHttp(sinoUtil.httpPrefix + '/api-business/getWorkReportsData', 'get', {
                type: type ? type : 1
            }, function (res) {
                if (res.status == 0) {
                    $('#performance_order_count').text('').text(res.data.completedOrderCount)
                    $('#new_quotation_count').text('').text(res.data.newQuotationCount)
                    $('#new_customer_count').text('').text(res.data.createCustomerCount)
                    $('#follow_customer_count').text('').text(res.data.followUpCustomerCount)
                    $('#send_mail_count').text('').text(res.data.sendEmailCount)
                    $('#receive_mail_count').text('').text(res.data.receiveEmailCount)
                    layer.close(_this.data.index)
                } else if (res.status == 10 || res.status == 11) {
                    window.parent.location.href = '/system/login'
                } else {
                    layer.close(_this.data.index)
                    layer.msg('获取工作简报数据失败', {
                        icon: 2,
                        time: 2000 //2秒关闭（如果不配置，默认是3秒）
                    })
                }
            }, function (error) {
                layer.close(_this.data.index)
                layer.msg('获取工作简报数据失败', {
                    icon: 2,
                    time: 2000 //2秒关闭（如果不配置，默认是3秒）
                })
            }, true)
        },
        goPage: function (obj) {
            var aArr = $(window.parent.document).find('.layui-nav .layui-nav-item a')
            if (aArr && aArr.length > 0) {
                layui.each(aArr, function (index, item) {
                    if ($(obj).data('url') == $(item).data('url')) {
                        item.click()
                    }
                })
            }
        }
    }

    $(function () {
        page.start()
    })
})